const KoaRouter = require('koa-router');
const bcrypt = require('bcryptjs'); //密码加密模块
const jwt = require('jsonwebtoken'); //用于签发、解析`token`
const CONFIG = require('../../../config/index');

let Router = new KoaRouter()

const UserlModel = require('../../../models/User');
/* 
    @route POST /login
    @params {userName,passWord}
    @desc 登录接口
    @return {token}
*/
Router.post('/', async (ctx) => {
    let userName = ctx.request.body.userName
    let passWord = ctx.request.body.passWord
    // 检查用户名是否存在
    const findResult = await UserlModel.find({
        userName: userName
    })
    if (findResult.length == 0) {
        ctx.body = {
            code: 1,
            data: {},
            message: '此用户名不存在'
        }
    } else {
        // 验证加密的密码
        let checketResult = bcrypt.compareSync(passWord, findResult[0].passWord);
        if (checketResult) {
            // 登陆成功后设置id
            // ctx.session.sessionID = 'testSessionId'
            // 登陆成功后返回token
            const payload = {
                id:findResult[0].id,
                name:findResult[0].userName
            }
            const token = jwt.sign( payload, CONFIG.secret, { expiresIn: '4h' });
            ctx.body = {
                code: 0,
                data: {
                    // session: ctx.session.sessionID
                    token:'Bearer '+token
                },
                message: '登陆成功'
            }
        } else {
            ctx.body = {
                code: 1,
                data: {

                },
                message: '密码错误'
            }
        }
    }


})


module.exports = Router.routes();